package logger

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"time"
)

var LG *zap.Logger

func InitLogger() (err error) {
	// 配置日志轮转
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "./k8s-dash.log", // 日志文件路径
		MaxSize:    100,              // 单个日志文件最大大小(MB)
		MaxBackups: 7,                // 保留旧日志文件的最大数量
		MaxAge:     7,                // 保留旧日志文件的最大天数
		Compress:   true,             // 是否压缩/归档旧日志文件
	}

	encoderConfig := zapcore.EncoderConfig{
		TimeKey: "time",
		//LevelKey:       "level",
		//NameKey:        "logger",
		//CallerKey:      "caller",
		//FunctionKey:    zapcore.OmitKey,
		//MessageKey:     "msg",
		//StacktraceKey:  "stacktrace",
		//LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseColorLevelEncoder,
		EncodeTime:     getCustomTimeEncoder,
		EncodeDuration: zapcore.StringDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}

	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		zapcore.AddSync(lumberJackLogger),
		zapcore.InfoLevel,
	)

	LG = zap.New(core, zap.AddCaller())
	zap.ReplaceGlobals(LG)
	zap.L().Info("init logger success")
	return
}

// CustomTimeEncoder 自定义日志输出时间格式
func getCustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(t.Format("2006/01/02 - 15:04:05.000"))
}
